package cn.xinfei.xdecision.engine.runner.producer;

import cn.xinfei.xdecision.common.utils.util.JsonUtils;
import cn.xinfei.xdecision.engine.runner.executor.model.EngineNodeLog;
import cn.xinfei.xdecision.engine.runner.service.DecisionResultDetailService;
import cn.xinfei.xdecision.nacos.NacosSwitchProperties;
import com.dianping.cat.Cat;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;

@Slf4j
@Service
public class DecisionProducer extends AbsDecisionProducer {


    @Autowired
    private DecisionResultDetailService decisionResultDetailService;


    @Autowired
    @Qualifier("nodeLogThreadPool")
    public ExecutorService nodeLogThreadPool;

//    public void sendNodeLog(EngineNodeLog engineNodeLog) {
//        XDecisionMessage msg = new XDecisionMessage();
//        try {
//            String decisionId = PipelineContextHolder.getDecisionId();
//            String bizId = PipelineContextHolder.getRequestId();
//
//            //补充上决策结果
//            engineNodeLog.getIps().push("p_" + IpUtil.getIpAddress());
////            String nodeLogs = JsonUtils.toJsonString(engineNodeLog);
//            String nodeLogs = JsonUtils.toJsonString(engineNodeLog);
//
//            msg.setData(nodeLogs);
////            msg.setMsgId(bizId + "_" + decisionId + "_" + engineNodeLog.getEngineCode() + "_" + engineNodeLog.getNodeCode());
//            String nodeCode = engineNodeLog.getNodeCode();
//            msg.setMsgId(bizId + "_" + decisionId + "_" + nodeCode);
//            msg.setKey(bizId);
//
//            log.info("message send start message id={}", msg.getMsgId());
//
//
//        } catch (Exception exception) {
//            log.error("send log fail . msg={}", JsonUtils.toJsonString(msg), exception);
//            Metrics.counter("xengine_nodelog_exception_total").increment();
//        }
//    }

    public void sendNodeLog(EngineNodeLog engineNodeLog) {
        String message = JsonUtils.toJsonString(engineNodeLog);
        nodeLogThreadPool.submit(() -> {
            try {
                if (NacosSwitchProperties.getNacosSwitchProperties().isDebugLog()) {
                    log.info("message:{}", message);
                }
                boolean resultDetail = decisionResultDetailService.saveEngineNodeLog(message);
                Metrics.counter("xdecision_consumer_total", Tags.of("topic", resultDetail + "")).increment();
            } catch (Throwable e) {
                Metrics.counter("xdecision_consumer_total", Tags.of("topic", "exception")).increment();
                Cat.logError(e);
                log.error("nodeLogInsertFail msg={},message={}", e.getMessage(), message, e);
                try {
                    boolean resultDetail = decisionResultDetailService.saveEngineNodeLog(message);
                    log.info("nodeLogInsertResult:{}", resultDetail);
                } catch (Throwable e1) {
                    Metrics.counter("xdecision_consumer_total", Tags.of("topic", "exception")).increment();
                    Cat.logError(e);
                    log.error("nodeLogInsertFail retryFail msg={}", e.getMessage(), e);
                }
            }
        });
    }


//    public void sendQueryLog(Set<String> varCodes, long respond, String response, String type) {
//        StateTransmitModel stateContext = XDecisionContext.getContext().getStateContext();
//        EngineResultEnum engineResultEnum = stateContext.getEngineResultEnum();
//        DecisionDataQueryLog decisionDataQueryLog = new DecisionDataQueryLog();
//        decisionDataQueryLog.setDecisionId(PipelineContextHolder.getDecisionId());
//        decisionDataQueryLog.setRequestId(PipelineContextHolder.getRequestId());
//        decisionDataQueryLog.setEngineCode(PipelineContextHolder.getEngineCode());
//        decisionDataQueryLog.setEngineName(PipelineContextHolder.getEngineName());
//        decisionDataQueryLog.setEngineVersion(PipelineContextHolder.getEngineVersion());
//        decisionDataQueryLog.setType(RiskDataApiAdapter.CollectTypeEnum.CREDIT_FETCH.name());
//        decisionDataQueryLog.setVarCodes(varCodes);
//
//        decisionDataQueryLog.setRespond(respond);
//        decisionDataQueryLog.setCode(engineResultEnum.getCode());
//        decisionDataQueryLog.setResponse(response);
//
//        XDecisionMessage msg = new XDecisionMessage();
//        try {
//            String decisionId = PipelineContextHolder.getDecisionId();
//            String bizId = PipelineContextHolder.getRequestId();
//
//            String nodeLogs = JsonUtils.toJsonString(decisionDataQueryLog);
//            msg.setData(nodeLogs);
//            msg.setMsgId(bizId + "_" + decisionId + "_" + type);
//            msg.setKey(bizId);
//
//
//            log.info("message send start message id={},nodeLogTopic={}", msg.getMsgId(), queryLogTopic);
//            sendAsync(queryLogTopic, msg,0);
//
//        } catch (Exception exception) {
//            log.error("send query xdata  log fail .nodeLogTopic={},msg={}", queryLogTopic, JsonUtils.toJsonString(msg), exception);
//            Cat.logError(exception);
//            Metrics.counter("xengine_QueryLog_exception_total").increment();
//        }
//    }


}
